"use strict";

var dataGridObj = {
    $dg: undefined,
    init: function () {

        var total = 0;
        var pageSize = 20;
        var pageNum = 1;
        if (this.$dg == undefined) {
            // 设置table选择器，用来生成datagrid
            this.$dg = $('#dataGridTable');
        }
        if (this.$dg.length > 0) {
            this.$dg.datagrid({
                // 响应式布局
                url:contextPath+'/console/appNode/loadNodeByPage',
                loadMsg: '加载中...',
                fit: true,
                columns: [[
                    {field:'nodeType',title:'图标',width:'5%',align:'center',
                        formatter:function (value,row) {
                            if(value) {
                                switch (value) {
                                    case "tomcat":
                                        return '<span class="font_28"><i class="icon ico-tomcat" ></i></span>';
                                        break;
                                    case "http":
                                        return '<span class="font_28"><i class="icon ico-http"></i></span>';
                                        break;
                                    case "redis":
                                        return '<span class="font_28"><i class="icon ico-redis"></i></span>';
                                        break;
                                    case "mysql":
                                        return '<span class="font_28"><i class="icon ico-mysql"></i></span>';
                                        break;
                                    case "oracle":
                                        return '<span class="font_28"><i class="icon ico-oracle"></i></span>';
                                        break;
                                    default:
                                        break;
                                }
                            }
                    }},
                    {field:'nodeName',title:'中间件名称',width:'12%',align:'center'},
                    {field:'appName',title:'所属应用',width:'12%',align:'center'},
                    {field:'hostName',title:'主机',width:'12%',align:'center'},
                    {field:'hostIp',title:'主机Ip',width:'12%',align:'center'},
                    {field:'basePath',title:'部署路径',width:'15%',align:'center'},
                    {field:'remark',title:'描述',width:'15%',align:'center'},
                    {field:'status',title:'状态',width:'5%',align:'center',
                        formatter: function (value, row, index) {
                            return '<input id='+row.nodeCode+' />';
                        }
                    }
                ]],

                //分组
                groupField:'hostIp',
                view:groupview,
                groupFormatter:function(value, rows){
                    return '所属主机IP: '+ value + ' - 中间件个数（' + rows.length +'）';
                },
                groupStyler:function () {
                  return "";
                },


                rownumbers: true,
                rownumberWidth: 70,
                singleSelect: true,
                emptyMsg:'暂无数据',
                toolbar: [{
                    id:"easyuiAddBtn",
                    text: '新增',
                    iconCls: 'icon-add',
                    plain:true,
                    handler: function () {
                        dataGridObj.goAdd();
                    }
                },{
                    id:"easyuiUptBtn",
                    text: '编辑',
                    iconCls: 'icon-edit',
                    plain:true,
                    handler: function () {
                        dataGridObj.goUpdate();
                    }
                },{
                    id:"easyuiDelBtn",
                    text: '删除',
                    iconCls: 'icon-remove',
                    plain:true,
                    handler: function () {
                        dataGridObj.doDeleteNode();
                    }
                },{
                    id:"easyuiAttrBtn",
                    text: '属性管理',
                    iconCls: 'icon-filter',
                    plain:true,
                    handler: function () {
                        dataGridObj.doAttrMgr();
                    }
                }],
                onLoadSuccess:function (data) {
                    //渲染启用开关
                    data.rows.forEach(function(value, index, array) {
                        value.nodeNameTemp = value.nodeName;
                        renderSwitchBtn(value);
                    });

                    //判断运维用户是否有读写权限，开关工具栏功能按钮
                    toolbarSwitch();
                }
            });
            // 重新赋值：获取渲染后的datagrid
            this.$dg = $('#dataGridTable');
            // 渲染成功，返回true
            return true;
        }
        return false;
    },
    // 新增，调Dialog打开方法，并且可编辑
    goAdd: function () {
        dialogObj.openAdd(contextPath + '/console/appNode/add');
        // $('#appCode').combobox('setValue', "");
        // $('#hostCode').combobox('setValue', "");
        // $('#status').combobox('setValue', 1);
        // $('#nodeType').combobox('setValue', "");
        // $('#protocol').combobox('setValue', "");
        //
        //
        // $('#nodeName').textbox('setValue', "");
        // $('#servicePort').textbox('setValue', "");
        // $('#dbUser').textbox('setValue', "");
        // $('#dbPwd').textbox('setValue', "");
        //
        // $('#remark').val("");
        // $('#basePath').val("");
        $("tr[name^=attr_]").hide();
        $("input[vailname^=attr_]").textbox("disableValidation");

        $("#dataForm").form("reset");
    },
    // 修改，调Dialog打开方法，并且可编辑
    goUpdate: function () {
        var selected = this.$dg.datagrid('getSelected');
        //console.log(selected);
        selected.nodeNameTemp = selected.nodeName;
        selected.nodeTypeTemp = selected.nodeType;
        selected.id = selected.nodeCode;
        $("tr[name^=attr_]").hide();

        $("input[vailname^=attr_]").textbox("disableValidation");
        $("input[vailname^=attr_]").textbox("clear");
        switch (selected.protocol){
            case "http":
                $("tr[name=attr_url]").show();
                $("#url").textbox("enableValidation");
                break;
            case "https":
                $("tr[name=attr_url]").show();
                $("#url").textbox("enableValidation");
                break;
            case "redis":
                $("tr[name=attr_redis]").show();
                $("#redisPwd").textbox("enableValidation");
                break;
            case "mysql":
                $("tr[name=attr_db]").show();
                $("#input[vailname^=attr_db]").textbox("enableValidation");
                break;
            case "tcp":
                break;
            default:

        }
        dialogObj.openUpdate(selected,contextPath + '/console/appNode/update');
    },
    // 删除中间件
    doDeleteNode: function () {
        // 获取选中的行
        var row = this.$dg.datagrid('getSelected');
        if (row) {
            apexLayer.Confirm("您确认删除应用吗？",
                "删除应用",
                "确认",
                "取消",
                function () {
                    Ajax({
                        url: contextPath + "/console/appNode/delete",
                        isMask: true,
                        data: {
                            "nodeCode":row.nodeCode,
                            "hostCode":row.hostCode
                        },
                        success: function (data) {
                            if (data.code>0) {
                                apexLayer.Msg(data.note, 1000, function () {
                                    dataGridObj.$dg.datagrid("reload");
                                });
                            } else {
                                apexLayer.Error("删除失败:" + data.note);
                            }
                        }
                    });
                }
            );
        } else {
            apexLayer.Warn('请先选择一条记录，才能进行删除操作！');
        }
    },
    doAttrMgr:function (callback) {
        var row = this.$dg.datagrid('getSelected');
        if (row) {
            taskQueryParams.nodeCode = row.nodeCode;
            taskQueryParams.hostCode = row.hostCode;
            taskQueryParams.basePath = row.basePath;

            $("#templateTask-dlg").dialog("open");
        } else {
            apexLayer.Warn('请先选择一条记录，才能进行删除操作！');
        }
    }
};

/**
 * 渲染启用开关
 * @param value
 */
function renderSwitchBtn(value){
    $("#"+value.nodeCode).switchbutton({
        width:50,
        height:20,
        onText:'ON',
        offText:'OFF',
        checked:!value.status=="0",
        onChange:function(checked){
            setTimeout(function(){
                var row = dataGridObj.$dg.datagrid('getSelected');
                var rowIndex = dataGridObj.$dg.datagrid('getRowIndex',row);
                row.status = checked?"1":"0";
                row.nodeNameTemp = row.nodeName;
                Ajax({
                    url:contextPath+"/console/appNode/update",
                    data:row,
                    success:function(data){
                        if(data.code>0){
                            dataGridObj.$dg.datagrid("updateRow",{index:rowIndex,row:row});
                        }else{
                            apexLayer.Error(data.note);
                        }
                    }
                });
            },200);
        }
    });
}
var appList=[],hostList=[],templateList=[];
$(function () {

    dataGridObj.init();
    dialogObj.init("add-dlg","dataForm");
    // 渲染Dialog
    $('#add-dlg').dialog({
        width: 850,
        height: 'auto',
        closed: true,
        cache: false,
        modal: true,
        shadow: false,
        buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                dialogObj.submiHandler("dataGridTable");
            }
        }],
        onClose: function () {
            // 还原Dialog
            dialogObj.reset();
        }
    });

    /**
     * 渲染任务管理的dom
     */
    dataGridTask.renderTaskDialog();

    Ajax({//所属应用
        url: contextPath + "/console/app/getAllApp",
        isMask: true,
        timeout: 0,
        data: {},
        success: function (data) {
            appList = data;
            var $appObj = $('#appCode');
            $appObj.combobox({
                data:appList,
                valueField: 'appCode',
                textField: 'appName',
                editable: false,
                panelHeight:　'auto',
                prompt:　'----请选择----',
                onLoadSuccess: function (data) {
                },
                onLoadError: function () {

                },
                onShowPanel: function () {
                    // 动态调整下拉高度
                    if (appList && appList.length > 10) {
                        $(this).combobox('panel').height(285);
                    }
                },
                onChange: function (value) {
                }
            });
            $("#search_appCode").combobox({
                data:appList,
                valueField: 'appCode',
                textField: 'appName',
                editable: false,
                panelHeight:　'auto',
                onLoadSuccess: function (data) {
                },
                onLoadError: function () {

                },
                onShowPanel: function () {
                    // 动态调整下拉高度
                    if (appList && appList.length > 10) {
                        $(this).combobox('panel').height(285);
                    }
                },
                onChange: function (value) {
                }
            });
        }
    });

    Ajax({//主机列表
        url: contextPath + '/console/host/getAllHost',
        isMask: true,
        timeout: 0,
        data: {},
        success: function (data) {
            hostList = data;
            var $hostObj = $('#hostCode');
            $hostObj.combobox({
                data:hostList,
                valueField: 'hostCode',
                textField: 'hostName',
                editable: false,
                panelHeight:　'auto',
                prompt:　'----请选择----',
                formatter: function(data){
                    if(data.hostName === '----请选择----'){
                        return data.hostName;
                    }
                    return data.hostName+'['+data.hostIp+']';
                },
                onLoadSuccess: function (data) {
                    // 缓存上游系统列表，模块datagrid初始化时会用到该数据
                    hostList = data;
                },
                onLoadError: function () {

                },
                onShowPanel: function () {
                    // 动态调整下拉高度
                    if (hostList && hostList.length > 10) {
                        $(this).combobox('panel').height(285);
                    }
                },
                onChange: function (value) {
                }
            });
            $("#search_hostCode").combobox({
                data:hostList,
                valueField: 'hostCode',
                textField: 'hostName',
                editable: false,
                panelHeight:　'auto',
                onLoadSuccess: function (data) {
                },
                onLoadError: function () {

                },
                onShowPanel: function () {
                    // 动态调整下拉高度
                    if (hostList && hostList.length > 10) {
                        $(this).combobox('panel').height(285);
                    }
                },
                onChange: function (value) {
                }
            });
        }
    });

    $("#dbAttr").hide();

    $("#nodeType").combobox({
        onSelect: function(record){
            switch (record.value){

            }
        }
    });


    $("#protocol").combobox({
        onSelect: function(record){
            $("tr[name^=attr_]").hide();
            $("input[vailname^=attr_]").textbox("disableValidation");
            $("input[vailname^=attr_]").textbox("clear");
            switch (record.value){
                case "http":
                    $("tr[name=attr_url]").show();
                    $("#url").textbox("enableValidation");
                    break;
                case "https":
                    $("tr[name=attr_url]").show();
                    $("#url").textbox("enableValidation");
                    break;
                case "redis":
                    $("tr[name=attr_redis]").show();
                    $("#redisPwd").textbox("enableValidation");
                    break;
                case "mysql":
                    $("tr[name=attr_db]").show();
                    $("#input[vailname^=attr_db]").textbox("enableValidation");
                    break;
                case "tcp":
                    break;
                default:

            }
        }
    });


});

function searchByCondition(num,size) {
    var status = $("#search_status").combobox("getValue");
    var appCode = $("#search_appCode").combobox("getValue");
    var hostCode = $("#search_hostCode").combobox("getValue");
    var url = contextPath+'/console/appNode/loadNodeByPage';
    $.get(
        url,
        {
            status:status,
            appCode:appCode,
            hostCode:hostCode,
        },
        function (data) {
            dataGridObj.$dg.datagrid('loadData', data);
        },
        'json'
    );
}
function resetCondition() {
    $("#searchContainer .easyui-textbox").each(function () {
       $(this).textbox('setValue', "");
    });
    $("#searchContainer .easyui-combobox").each(function () {
       $(this).combobox('setValue', "");
    });
    searchByCondition();
}
